package com.atguigu.gulimail.ware.service.impl;


import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.mq.StockDetailTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.gulimail.ware.dao.WareSkuDao;
import com.atguigu.gulimail.ware.entity.WareOrderTaskDetailEntity;
import com.atguigu.gulimail.ware.entity.WareOrderTaskEntity;
import com.atguigu.gulimail.ware.entity.WareSkuEntity;
import com.atguigu.gulimail.ware.fegin.MemberFeignService;
import com.atguigu.gulimail.ware.fegin.OrderFeignService;
import com.atguigu.gulimail.ware.fegin.ProductFeignService;
import com.atguigu.gulimail.ware.service.WareOrderTaskDetailService;
import com.atguigu.gulimail.ware.service.WareOrderTaskService;
import com.atguigu.gulimail.ware.service.WareSkuService;
import com.atguigu.gulimail.ware.vo.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.rabbitmq.client.Channel;
import lombok.Data;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;


import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@RabbitListener(queues ="STOCK-RELEASE-STOCK-QUEUE")
@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    WareSkuDao wareSkuDao;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    WareOrderTaskService wareOrderTaskService;

    @Autowired
    OrderFeignService orderFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        /**
         * skuId: 1
         * wareId: 2
         */
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(skuId)) {
            queryWrapper.eq("sku_id", skuId);
        }
        if (!StringUtils.isEmpty(wareId)) {
            queryWrapper.eq("ware_id", wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        List<WareSkuEntity> wareSkuEntities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (wareSkuEntities == null || wareSkuEntities.size() == 0) {
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            try {
                R info = productFeignService.info(skuId);
                Map<String, Object> data = (Map<String, Object>) info.get("skuInfo");
                if (info.getcode() == 0) {
                    wareSkuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch (Exception e) {

            }
            wareSkuDao.insert(wareSkuEntity);
        } else {
            wareSkuDao.updateStock(skuId, wareId, skuNum);
        }
    }

    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
            SkuHasStockVo vo = new SkuHasStockVo();
            WareSkuEntity wareSkuEntity = baseMapper.selectById(skuId);
            Integer count = wareSkuEntity.getStock();
            vo.setSkuId(skuId);
            vo.setHasStock(count == null ? false : count > 0);
            return vo;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public FareVo getFare(Long addrId) {
        R info = memberFeignService.addrInfo(addrId);
        FareVo fareVo = new FareVo();
        MemberAddressVo data = info.getDatas("memberReceiveAddress", new TypeReference<MemberAddressVo>() {
        });

        if (data != null) {
            String phone = data.getPhone();
            String substring = phone.substring(phone.length() - 1, phone.length());

            fareVo.setMemberAddressVo(data);
            fareVo.setFare(new BigDecimal(substring));

            return fareVo;
        }
        return null;
    }

    // 默认只要是运行时异常都会回滚
    @Transactional(rollbackFor = NoStockException.class)
    @Override // 为订单锁定库存
    public Boolean orderLockStock(WareSkuLockVo skuLockVo) {

        // 保存库存工作单详情
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(skuLockVo.getOrderSn());
        wareOrderTaskService.save(taskEntity);

        // 1、找到每个商品在哪个仓库都有库存
        List<OrderItemVo> locks = skuLockVo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            stock.setSkuId(item.getSkuId());
            stock.setCount(item.getCount());
            // 查询这个商品在哪里有库存
            List<Long> wareIds = wareSkuDao.listWareIdHasStock(item.getSkuId());
            stock.setWareId(wareIds);
            return stock;
        }).collect(Collectors.toList());

        Boolean allLock = true;
        // 2、锁定库存
        for (SkuWareHasStock hasStock : collect) {
            Boolean skuStocked = false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();
            if (wareIds == null || wareIds.size() == 0) {
                // 没有任何仓库有这个商品的库存
                throw new NoStockException(skuId);
            }
            for (Long wareId : wareIds) {
                // 成功返回1 ，失败返回0
                Long count = wareSkuDao.lockSkuStock(skuId, wareId, hasStock.getCount());
                if (count == 1) {
                    // 当前仓库锁成功,重试下一个仓库
                    skuStocked = true;
                    WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity(null, skuId, "", hasStock.getCount(), taskEntity.getId(), wareId, 1);
                    wareOrderTaskDetailService.save(entity);
                    StockLockedTo stockLockedTo = new StockLockedTo();
                    stockLockedTo.setId(taskEntity.getId());
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(entity, stockDetailTo);
                    // 只发id不行
                    stockLockedTo.setDetail(stockDetailTo);
                    rabbitTemplate.convertAndSend("STOCK-EVENT-EXCHANGE", "stock.locked", stockLockedTo);
                    break;
                } else {
                    // 当前仓库锁失败,重试下一个仓库


                }
            }
            if (skuStocked == false) {
                // 当前商品所有仓库都没锁住
                throw new NoStockException(skuId);
            }
        }

        // 3、肯定全部都是锁定成功的
        return true;
    }


    //  1、库存自动解锁,如果订单已付款则直接扣除库存
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) {
        StockDetailTo detail = to.getDetail();
        Long skuId = detail.getSkuId();
        Long detailId = detail.getId();
        /** 1、查询数据库关于这个订单的锁定库存信息
         *      有 证明库存锁定成功
         *          解锁：订单情况
         *              1、没有这个订单。必须解锁
         *              2、有这个订单，不是解锁库存
         *                  查看订单状态： 已取消 解锁库存
         *                              未取消 不能解锁
         *      没有 库存锁定失败，库存回滚了，这种情况无需解锁
         *
         */
        WareOrderTaskDetailEntity byId = wareOrderTaskDetailService.getById(detailId);
        if (byId != null) {
            // 有则解锁
            Long id = to.getId();
            WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(id);
            String orderSn = taskEntity.getOrderSn();
            // 获取订单信息
            R r = orderFeignService.getOrderStatus(orderSn);
            // 查询订单是否成功
            if (r.getcode() == 0) {
                OrderVo orderVo = r.getData("data", new TypeReference<OrderVo>() {
                });
                // 已付款
                if (orderSn != null && orderVo.getStatus() == 1){
                    WareOrderTaskDetailEntity updateEntity = new WareOrderTaskDetailEntity();
                    updateEntity.setId(byId.getId());
                    updateEntity.setLockStatus(3);
                    wareOrderTaskDetailService.updateById(updateEntity);
                    baseMapper.payedDecrease(detail.getSkuId(),detail.getWareId(),detail.getSkuNum());
                    try {
                        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                // 已过期
                if (orderVo == null || orderVo.getStatus() == 4) {
                    // 当前工作单详情状态为1 已锁定但是未解锁才可以解锁
                    if (byId.getLockStatus() == 1) {
                        // 订单已经被取消了，才能解锁库存
                        unLockStock(skuId, detail.getWareId(), detail.getSkuNum(), detailId);

                        WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity();
                        // 更新库存工作单的状态
                        entity.setId(detailId);
                        entity.setLockStatus(2);
                        wareOrderTaskDetailService.updateById(entity);
                        try {
                            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        } else {
            // 无需解锁
        }

    }


//     2、 订单直接解锁
    @Transactional
    @RabbitHandler
    public void handleOrderCloseRelease(String orderSn, Message message, Channel channel) {
        System.out.println("订单关闭准备解锁库存。。");
        // 查一下最新的库存的状态，防止重复解锁库存
        WareOrderTaskEntity entity = wareOrderTaskService.getByOrderSn(orderSn);
        Long id = entity.getId();
        try {
            // 按照库存工作单，没有解锁库存的，进行解锁
            List<WareOrderTaskDetailEntity> list = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>()
                    .eq("task_id", id)
                    .and(obj -> {
                        obj.eq("lock_status", 1);
                    }));
            if (list != null && list.size() > 0) {
                for (WareOrderTaskDetailEntity wEntity : list) {
                    unLockStock(wEntity.getSkuId(), wEntity.getWareId(), wEntity.getSkuNum(), wEntity.getId());
                }
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            try {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    private void unLockStock(Long skuId, Long wareId, Integer num, Long taskDetailId) {
        wareSkuDao.unLockStock(skuId, wareId, num);
    }
}

@Data
class SkuWareHasStock {
    private long skuId;
    private Integer count;
    private List<Long> wareId;
}